const { createBundleRenderer } = require('vue-server-renderer')
const config = require('../../configure')
const fs = require('fs')

const rendererArgs = config.isDev ? require('./dev') : require('./pro')

const template = fs.readFileSync(config.templateFileName, 'utf-8')
const cache = {}

module.exports = async () => {
  let renderer;
  
  if (config.isDev || !(renderer = cache.renderer)) {
    const manifest = await rendererArgs.getManifest()

    if (!manifest) {
      throw 'lack manifest file, Did you pack client'
    } else if (!rendererArgs.bundle) {
      throw 'lack bundle file, Did you pack client'
    }

    renderer = createBundleRenderer(rendererArgs.bundle, {
      runInNewContext: false,
      template,
      clientManifest: manifest
    })
  }
  return renderer
}